#include "Player.h"
#include <iostream>

Player::Player(Input *receiver, ICursorControl *cursor, ISceneManager *smgr, LogicManager *lm) {

    _receiver = receiver;
    _cursor = cursor;
    _smgr = smgr;
    _current = NULL;
    _lm = lm;
}

void Player::update(irr::u32 current_time, irr::u32 last_time)
{
    if(_receiver->mouse.left)
    {
        _receiver->mouse.left = false;
        core::position2d<s32> mouse_pos = _cursor->getPosition();
        //core::line3df line = _smgr->getSceneCollisionManager()->getRayFromScreenCoordinates(mouse_pos, _smgr->getActiveCamera());
        //line.start.Y-=20;
        //ISceneNode* object = _smgr->getSceneCollisionManager()->getSceneNodeFromRayBB(line);
        ISceneNode* object = _smgr->getSceneCollisionManager()->getSceneNodeFromScreenCoordinatesBB(mouse_pos, 1);
        if(object) 
        {
            irr::s32 id = object->getID();
            ILogicNode * ln= _lm->getNodeFromID(id);
            if(ln != NULL)
            {		
                if(_current != NULL)
                    ((Fighter *)_current)->setColor(0,255,0);

                _current = ln;
                ((Fighter *)_current)->setColor(0,0,255);
            }
            else
            {
                if(_current != NULL)
                    ((Fighter *)_current)->setColor(0,255,0);
                _current = NULL;
            }
        }
        else 
        {
            if(_current != NULL)
                ((Fighter *)_current)->setColor(0,255,0);
            _current = NULL;
        }
    }
    else if(_receiver->mouse.right && _current != NULL)
    {
        _receiver->mouse.right = false;
        core::position2d<s32> mouse_pos = _cursor->getPosition();
        core::line3df line = _smgr->getSceneCollisionManager()->getRayFromScreenCoordinates(mouse_pos, _smgr->getActiveCamera());
        core::vector3df destination;
        //destination.Y=0;
        ISceneNode* object = _smgr->getSceneCollisionManager()->getSceneNodeFromScreenCoordinatesBB(mouse_pos, 1);
        if(object) 
        {
            ITriangleSelector* ts = _smgr->createTerrainTriangleSelector((ITerrainSceneNode *)object);
            object->setTriangleSelector(ts);
            ts->drop();
            ts = object->getTriangleSelector();
            core::vector3df outCollisionPoint;
            core::triangle3df outTriangle;
            bool t = _smgr->getSceneCollisionManager()->getCollisionPoint(line, ts, outCollisionPoint, outTriangle);
            destination = outCollisionPoint;

            _current->move(destination);
        }
    }
}

